package com.platform.common.utils;

import java.io.*;

/**
 * amr文件工具
 */
public class AmrDurationUtils {
    private static final int AMR_FRAME_DURATION_MS = 20; // 每个AMR帧是20ms

    // AMR-NB 帧大小表（单位：字节）
    private static final int[] packedSizeNB = {13, 14, 16, 18, 20, 21, 27, 32};

    // AMR-WB 帧大小表（单位：字节）
    private static final int[] packedSizeWB = {13, 17, 19, 21, 25, 31, 37, 41, 47};

    /**
     * 文件头解析
     */
    public static int estimateAmrDuration(InputStream inputStream) {
//        FileInputStream fileInputStream = new FileInputStream(filePath);
        try (DataInputStream dis = new DataInputStream(inputStream)) {
            byte[] header = new byte[6];
            dis.readFully(header); // 读取AMR文件头

            if (!(new String(header).equals("#!AMR\n") || new String(header).equals("#!AMR-WB\n"))) {
                throw new IOException("Not a valid AMR file.");
            }

            boolean isWB = new String(header).equals("#!AMR-WB\n");

            int frameCount = 0;
            while (dis.available() > 0) {
                int octet = dis.readUnsignedByte(); // AMR帧的第一个字节包含了帧模式信息
                int mode = (octet >> 3) & 0x0F; // 获取帧模式

                if (mode >= 0 && mode <= 7) {
                    // 根据模式选择正确的帧大小数组
                    int[] packedSize = isWB ? packedSizeWB : packedSizeNB;

                    // 跳过剩余的帧数据，长度取决于帧模式
                    if (mode < packedSize.length) {
                        int size = packedSize[mode];
                        dis.skipBytes(size - 1); // 减去已经读取的第一个字节
                        frameCount++;
                    } else {
                        // 如果模式超出范围，则可能是无效帧或文件损坏
                        break;
                    }
                } else {
                    // 处理SID（静音描述）帧或其他特殊情况
                    // 这里简化处理，直接忽略这些帧
                    continue;
                }
            }

            double duration = frameCount * AMR_FRAME_DURATION_MS / 1000.0; // 将毫秒转换为秒
            return(int) Math.ceil(duration);
        } catch (IOException e) {
            throw new RuntimeException("Error reading AMR file", e);
        }
    }

    /**
     * ffmpeg 解析
     */
    public static double getAmrDuration(String filePath) {
        double duration = -1;
        ProcessBuilder builder = new ProcessBuilder("ffmpeg", "-i", filePath);
        builder.redirectErrorStream(true);
        try {
            String line;

            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while ((line = reader.readLine()) != null && duration < 0) {
                if (line.contains("Duration")) {
                    String[] parts = line.split(",")[0].split(": ");
                    String durationStr = parts[parts.length - 1];
                    duration = parseDuration(durationStr);
                }
            }
            reader.close();
            process.destroy();

        } catch (IOException e) {
            throw new RuntimeException("Error reading AMR file", e);
        }
        return duration;
    }

    public static double parseDuration(String durationStr) {
        String[] parts = durationStr.split(":");
        double hours = Double.parseDouble(parts[0]);
        double minutes = Double.parseDouble(parts[1]);
        double seconds = Double.parseDouble(parts[2].replaceAll("[^\\d.]", ""));
        return hours * 3600 + minutes * 60 + seconds;
    }

    public static void main(String[] args) throws FileNotFoundException {
        String amrFilePath = "/Users/zhaowei/Desktop/test/order-12-11/file/周杰伦-魔术先生.amr"; // 替换为你的amr文件路径
        double duration = estimateAmrDuration(new FileInputStream(amrFilePath));
        int durationRes = (int) Math.ceil(duration);
        System.out.println("Estimated Duration: " + durationRes + " seconds");

        double amrDuration = getAmrDuration(amrFilePath);
        System.out.println("Duration: " + amrDuration + " seconds");
    }


//    public static void main(String[] args) {
//        String amrFilePath = "/Users/zhaowei/Desktop/test/order-12-11/file/周杰伦-魔术先生.amr"; // 替换为你的amr文件路径
//        try {
//            getAmrDuration(amrFilePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
